# -*- coding: utf-8 -*-

#    OriginDB
#    Copyright (C) 2009  Jason Power <power.jg@gmail.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program; if not, write to the Free Software Foundation, Inc.,
#    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

from chemdb import dbHandle

import hashlib

def login(db, host, username='', password=''):

	if not username or not password:
		dbHandle.reconnect('chemdb_min_user', 'origindb', db, host)
		dbHandle.setUid(-1)
		return

	hashPass = hashlib.md5(password)

	dbUid, dbPass = dbHandle.getUserInfo(username)

	if dbPass != hashPass.digest():
		raise ValueError, "Bad username / password"

	chemEncrypt = dbHandle.get('chem_pass', 'user', 'username', username)

	chemPass = crypt(chemEncrypt, int(hashPass.hexdigest(), 16))

	dbHandle.reconnect('chemdb_user', chemPass, db, host)
	dbHandle.setUid(dbUid)


def logout():
	dbHandle.reconnect('chemdb_min_user', 'origindb')
	dbHandle.setUid(-1)


def crypt (sequence, key):
	import random
	sign = (key > 0) * 2 - 1
	random.seed (abs (key * sign))
	s = ''
	for i in xrange (len (sequence)):
		r = random.randint (0, 255)
		s += chr ((ord (sequence [i]) + r * sign) % 256)
	return s

def changePass(oldPass, newPass):

	hashPass = hashlib.md5(oldPass)
	passwd = dbHandle.get('password', 'user', 'id', dbHandle.uid)

	if passwd != hashPass.digest():
		raise ValueError

	chemEncrypt = dbHandle.get('chem_pass', 'user', 'id', dbHandle.uid)

	chemPass = crypt(chemEncrypt, int(hashPass.hexdigest(), 16))

	hashPassNew = hashlib.md5(newPass)

	chemEncryptNew = crypt(chemPass, -1*int(hashPassNew.hexdigest(), 16))

	print "about to update password"

	dbHandle.updatePassword(dbHandle.uid, hashPassNew.digest(), chemEncryptNew)

def userLoggedIn():
	return dbHandle.userLoggedIn()